<!DOCTYPE html>

<html>
	<head>
		<title>Particle</title>
		<script type="text/javascript" src="../libs/three.js"></script>
		<script type="text/javascript" src="../libs/jquery-1.9.0.js"></script>
		<script type="text/javascript" src="../libs/stats.js"></script>
		<script type="text/javascript" src="../libs/dat.gui.js"></script>
		<script type="text/javascript" src="../libs/TrackballControls.js"></script>

		<link rel="stylesheet" type="text/css" href="../stylesheets/bootstrap.css">
		<link rel="stylesheet" type="text/css" href="../stylesheets/pixel-admin.css">
		<link rel="stylesheet" type="text/css" href="../stylesheets/widgets.css">
		<link rel="stylesheet" type="text/css" href="../stylesheets/rtl.css">
		<link rel="stylesheet" type="text/css" href="../stylesheets/themes.css">

		<style >
			body{
				/* set margin to 0 and overflow to hidden, to use the complete page */

				margin: 0;
				overflow: hidden;
			}
		</style>
	</head>
	<body>

		<!-- Div which will hold the Output -->
		<div id="WebGL-output">
		</div>

		<!-- Div which will show the stats -->
		<div id="Stats-output">
		</div>

		<div id="modal" class="modal fade" tabindex="-1" role="dialog" style="display:none;">
			<div>
				<img src="../image/IMG_0033.JPG" width="400px" height="300px">
			</div>
			<div>
				<p>this is a example~~~</p>
			</div>
		</div>

		<script type="x-shader/x-vertex" id="vertexshader">

			attribute float size;
			attribute vec3 customColor;

			varying vec3 vColor;

			void main() {

				vColor = customColor;

				vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );

				gl_PointSize = size * ( 300.0 / length( mvPosition.xyz ) );

				gl_Position = projectionMatrix * mvPosition;

			}

		</script>

		<script type="x-shader/x-fragment" id="fragmentshader">

			uniform vec3 color;
			uniform sampler2D texture;

			varying vec3 vColor;

			void main() {

				gl_FragColor = vec4( color * vColor, 1.0 );

				gl_FragColor = gl_FragColor * texture2D( texture, gl_PointCoord );

				if ( gl_FragColor.a < ALPHATEST ) discard;

			}

		</script>

		<!-- Javascript code that runs our Three.js examples -->
		<script type="text/javascript">

			var trackball;
			var clock = new THREE.Clock();

			var uniforms, attributes;

			var PARTICLE_SIZE = 10;

			var raycaster, intersects;
			var mouse;
			var INTERSECTED;

			var sTexture = THREE.ImageUtils.loadTexture("image/IMG_0033.JPG");

			//once everything is loaded, we run our Three.js stuff.
			$(function () { 
 				var stats = initStats();
 				
 				//here we'll put the Three.js stuff
 				var scene = new THREE.Scene();
 				
 				//add camera and renderer
 				var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
 				
 				var renderer = new THREE.WebGLRenderer();
 				renderer.setClearColor(0xEEEEEE, 1.0);
 				renderer.setSize(window.innerWidth, window.innerHeight);
 				renderer.shadowMapEnabled = true;

 				//add Light
 				var ambientLight = new THREE.AmbientLight(0x0c0c0c);
 				scene.add(ambientLight);

		        camera.position.x = 0;
		        camera.position.y = 0;
		        camera.position.z = 330;
		        camera.lookAt(new THREE.Vector3(0, 0, 0));
		        document.getElementById("WebGL-output").appendChild(renderer.domElement);

		        document.addEventListener( 'mousemove', onDocumentMouseMove, false );
		        document.addEventListener( 'click', onDocumentMouseClick, false );
		        // document.addEventListener( 'mousedown', onDocumentMouseDown, false );
		        // document.addEventListener( 'mouseup', onDocumentMouseUp, false );
		        window.addEventListener( 'resize', onWindowResize, false );

		        trackball = new THREE.TrackballControls(camera);
				trackball.rotateSpeed = 0.01;
				trackball.zoomSpeed = 0.1;
				trackball.panSpeed = 0.01;
				trackball.minDistance = 330;
				trackball.maxDistance = 500;


		        var geom = new THREE.Geometry();

		        attributes = {
					size:        { type: 'f', value: [] },
					customColor: { type: 'c', value: [] },
				};

				uniforms = {
					color:   { type: "c", value: new THREE.Color( 0xffffff ) },
					texture: { type: "t", value: THREE.ImageUtils.loadTexture( "image/sprites/circle.png" ) }
					
				};

		        var shaderMaterial = new THREE.ShaderMaterial( {
					uniforms: uniforms,
					attributes: attributes,
					vertexShader: document.getElementById( 'vertexshader' ).textContent,
					fragmentShader: document.getElementById( 'fragmentshader' ).textContent,

					alphaTest: 0.9,
				} );

				var radius = 300;
				var rand = 30;		        
		        for(var i = 0; i < 10000; i++){
		        	var particle = initParticle(radius, rand);
		        	geom.vertices.push(particle);
		        }


		        var cloud = new THREE.PointCloud(geom, shaderMaterial);

	            var values_size = attributes.size.value;
				var values_color = attributes.customColor.value;

				var vertices = cloud.geometry.vertices;

				for( var v = 0,  vl = vertices.length; v < vl; v++ ) {
					values_size[ v ] = PARTICLE_SIZE;
					values_color[ v ] = new THREE.Color().setHSL( 0.01 + 0.1 * ( v / vl ), 1.0, 0.5 );
				}

	            scene.add(cloud);

	            //
		        raycaster = new THREE.Raycaster();
		        mouse = new THREE.Vector2();

		        var sphere;
		        var step = 0;
		        var cameraRadius = 400;
 				//add animation
 				render();
 				function render(){
 					stats.update();

 					var delta = clock.getDelta();
 					trackball.update(delta);

 					raycaster.setFromCamera(mouse, camera);
 					intersects = raycaster.intersectObject(cloud);

 					if ( intersects.length > 0 ) {
						if ( INTERSECTED != intersects[ 0 ].index ) {
							// attributes.size.value[ INTERSECTED ] = PARTICLE_SIZE;
							scene.remove(sphere);
							INTERSECTED = intersects[ 0 ].index;
							sphere = focusParticle();
							sphere.position.x = vertices[INTERSECTED].x;
							sphere.position.y = vertices[INTERSECTED].y;
							sphere.position.z = vertices[INTERSECTED].z;
							scene.add(sphere);
							// console.log(vertices[INTERSECTED]);
							// attributes.size.value[ INTERSECTED ] = PARTICLE_SIZE * 5;
							// attributes.size.needsUpdate = true;
						}
					} else if ( INTERSECTED !== null ) {
						// attributes.size.value[ INTERSECTED ] = PARTICLE_SIZE;
						scene.remove(sphere);
						// attributes.size.needsUpdate = true;
						INTERSECTED = null;
					}

 					requestAnimationFrame(render);
 					renderer.render(scene, camera);
 				};


				function onWindowResize() {

					camera.aspect = window.innerWidth / window.innerHeight;
					camera.updateProjectionMatrix();

					renderer.setSize( window.innerWidth, window.innerHeight );

				}

				function onDocumentMouseMove( event ) {

					event.preventDefault();

					mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
					mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

				}

				var cameraMouse = new THREE.Vector2();
				cameraMouse.x = 0;
				cameraMouse.y = 0;


				function onCameraMouseMove( event ){
					event.preventDefault();

					var x = ( event.clientX / window.innerWidth ) * 2 - 1;
					var y = - ( event.clientY / window.innerHeight ) * 2 + 1;

					var angleX = (x - cameraMouse.x) / 4 * Math.PI;
					var angleY = (y - cameraMouse.y) / 4 * Math.PI;

					// camera.rotation.y += angleX;
					// camera.rotation.x += angleY;
					

					var cx = camera.position.x;
					var cy = camera.position.y;
					var cz = camera.position.z;

					var tanx = cx / cz;
					var tany = cy / cz;
					var angleX_i = Math.atan(tanx);
					var angleY_i = Math.atan(tany);


					var radius_xz = Math.sqrt(cx * cx + cz * cz);
					cx = radius_xz * Math.sin(angleX_i + angleX);
					cz = radius_xz * Math.cos(angleX_i + angleX);

					var radius_yz = Math.sqrt(cy * cy + cz * cz);
					cy = radius_yz * Math.sin(angleY_i + angleY);
					cz = radius_yz * Math.cos(angleY_i + angleY);

					console.log(cx);
					console.log(cy);
					console.log(cz);

					camera.position.x = cx;
					camera.position.y = cy;
					camera.position.z = cz;

					camera.lookAt(scene.position);

					cameraMouse.x = x;
					cameraMouse.y = y;


				}

				function onDocumentMouseDown( event ){
					cameraMouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
					cameraMouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
					mouse.x = 2;
					mouse.y = 2;
					document.addEventListener( 'mousemove', onCameraMouseMove, false );
					document.removeEventListener( 'mousemove', onDocumentMouseMove, false );
				}

				function onDocumentMouseUp( event ){
					document.addEventListener( 'mousemove', onDocumentMouseMove, false );
					document.removeEventListener( 'mousemove', onCameraMouseMove, false );
				}

				function onDocumentMouseClick( event ){
					if(INTERSECTED != null){
						// $('#modal').addClass("show");
						// $('#modal').removeClass("fade");
						$("#modal").modal("show");
					}
				}

			});

			function initStats(){
				var stats = new Stats();
				stats.setMode(0);
				stats.domElement.style.position = 'absolute';
				stats.domElement.style.lefe = '0px';
				stats.domElement.style.top = '0px';
				$("#Stats-output").append(stats.domElement);
				return stats;
			}

			function initParticle(radius, rand){
				var x = 2 * radius * Math.random() - radius;
				var delta = Math.sqrt(radius * radius - x * x);
				var y = 2 * delta * Math.random() - delta;
				var z = Math.sqrt(delta * delta - y * y);
				if(Math.random() > 0.5){
					z = 0 - z;
				}
				return new THREE.Vector3(x + Math.random() * rand - rand / 2, y + Math.random() * rand - rand / 2,
					z + Math.random() * rand - rand / 2);
			}

			function focusParticle(){
				var focusGeom = new THREE.SphereGeometry(2, 50, 50);
				var focusMtl = new THREE.MeshBasicMaterial({color: 0xffffff});
				focusMtl.map = sTexture;
				var focusSphere = new THREE.Mesh(focusGeom, focusMtl);
				focusSphere.name = "focus";
				return focusSphere;
			}


		</script>

	</body>
</html>